package cn.sinjet.carassist;


import com.mgroup.wazehelper.R;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import cn.sinjet.myview.DoorOpenWarningView;
import cn.sinjet.myview.HintAlertDlg;
import cn.sinjet.viewmodel.IUpdateUI;
import cn.sinjet.viewmodel.OnMyDlgActionListener;
import cn.sinjet.viewmodel.PageDefine;
import cn.sinjet.viewmodel.ViewEvent;
import cn.sinjet.viewmodel.ViewModel;

public class SinjetUIActivity extends Activity implements IUpdateUI,OnClickListener {
	private final static String tag = "ui";
	private FrameLayout rootView;
	private ViewGroup mPageView;
    private DialogView mDialogView = null;
//    private EventManager mWpEventManager;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
//		if(MainModel.getIns().naviModel.getSettings().isKeepScreenOn)
//			getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		rootView = new FrameLayout(this);
		SinjetApplication.getInstance().addActivity(this);
		mDialogView = new DialogView(this);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		Log.d(tag, "onBackPressed");
//		mApp.sendSyncPageID(Constant.KEY_BACK_FLYPAGE);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		ViewModel.getIns().setInCommonActivity(false);
//		 mWpEventManager.send("wp.stop", null, null, 0, 0);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		rootView.removeAllViews();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
//		if(MainModel.getIns().naviModel.getSettings().isKeepScreenOn)
//			getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//		else 
//			getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON, WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
		ViewModel.getIns().setInCommonActivity(true);
		ViewModel.getIns().setUIListener(this);
		ViewModel.getIns().setContext(this);
		int pageId = ViewModel.getIns().getCurMyPage();
		jumpPage(PageDefine.getLayoutByPageId(pageId));
//		registerWakeupEvent();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d(tag, "ui onDestory");
	}

	public void jumpPage(int layout) {
		if (layout != 0) {
			try{
				mPageView = (ViewGroup) getLayoutInflater().inflate(layout, null);
				setUIViewProperty(mPageView);
				if(rootView == null) new FrameLayout(this);
				rootView.removeAllViews();
				rootView.addView(mPageView);
				setContentView(rootView);
			}catch(Exception e){
//				Log.d(tag, "catch Exception ="+e.toString());
				e.printStackTrace();
			}
		}
	}

	public void setUIViewProperty(ViewGroup vg) {
		for (int i = 0; i < vg.getChildCount(); i++) {
			View v = vg.getChildAt(i);
			if (v instanceof ViewGroup) {
				if(v.getId() != -1)  ViewModel.getIns().getUIMsgSaveCenter().restoreUIProperty(v);
				setUIViewProperty((ViewGroup) v);
			} else {
				ViewModel.getIns().getUIMsgSaveCenter().restoreUIProperty(v);
			}
		}
	}

	@Override
	public void resetContentView(int layout) {
		// TODO Auto-generated method stub
		Log.d(tag, "HAND_JUMP_PAGE_MESSAGE layout: " + layout);
		jumpPage(layout);
	}

	@Override
	public void finishActivity() {
		// TODO Auto-generated method stub
		finish();
	}

	
	@Override
	public void updateUI(Bundle data) {
		// TODO Auto-generated method stub
		if(mPageView == null) return;
		int viewId = data.getInt("id");
//		Log.d("ui", "sinjet ui update ui:"+viewId);
		if(viewId == -1) return;
		
		if(mDialogView.handleView(viewId)) return;
		
		View v = mPageView.findViewById(viewId);
		if(v != null){
			ViewModel.getIns().getUIMsgSaveCenter().restoreUIProperty(v);
		}
	}

	
	
	
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		Log.d(tag, "onClick in activity");
		ViewModel.getIns().onViewEvent(new ViewEvent(view.getId(), ViewEvent.CLICK));
	}
	/*@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		MainModel.getIns().naviModel.storeAppData();
	}*/
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
//		return super.onKeyUp(keyCode, event);
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			ViewModel.getIns().onBackKeyUp();
		}
		return true;
	}

	@Override
	public void showAlertDialog(String positive,String nagative, String content, final OnMyDlgActionListener actionListener) {
		// TODO Auto-generated method stub
		HintAlertDlg pswAlertDlg = new HintAlertDlg(this);
		pswAlertDlg.setButtonText(positive, nagative);
		pswAlertDlg.show(content, actionListener);
	}

	DoorOpenWarningView mDoorOpenWarningView = null;
	@Override
	public void showDoorWarn(int[] doors) {
		// TODO Auto-generated method stub
		if(doors == null || doors.length !=5) return;
		if(mDoorOpenWarningView == null)
			mDoorOpenWarningView = new DoorOpenWarningView(this,R.style.CustomDialog);
		if(mDoorOpenWarningView != null){
			mDoorOpenWarningView.showOsdView(doors[0],doors[1],doors[2],doors[3],doors[4]);
		}
	}
	
/*	void registerWakeupEvent(){
		// 唤醒功能打开步骤
        // 1) 创建唤醒事件管理器
        mWpEventManager = EventManagerFactory.create(SinjetUIActivity.this, "wp");

        // 2) 注册唤醒事件监听器
        mWpEventManager.registerListener(new EventListener() {
            @Override
            public void onEvent(String name, String params, byte[] data, int offset, int length) {
                Log.d("voice", String.format("event: name=%s, params=%s", name, params));
                try {
                    JSONObject json = new JSONObject(params);
                    if ("wp.data".equals(name)) { // 每次唤醒成功, 将会回调name=wp.data的时间, 被激活的唤醒词在params的word字段
                        String word = json.getString("word");
//                        onClkStartVoiceRecognizer();
//                        txtLog.append("唤醒成功, 唤醒词: " + word + "\r\n");
                    } else if ("wp.exit".equals(name)) {
//                        txtLog.append("唤醒已经停止: " + params + "\r\n");
                    }
                } catch (JSONException e) {
                    throw new AndroidRuntimeException(e);
                }
            }
        });

        // 3) 通知唤醒管理器, 启动唤醒功能
        HashMap params = new HashMap();
        params.put("kws-file", "assets:///WakeUp.bin"); // 设置唤醒资源, 唤醒资源请到 http://yuyin.baidu.com/wake#m4 来评估和导出
        mWpEventManager.send("wp.start", new JSONObject(params).toString(), null, 0, 0);
	}*/
	
/*	private void onClkStartVoiceRecognizer() {
		// TODO Auto-generated method stub
			Intent intent = new Intent(this, ApiActivity.class);
			intent.putExtra("isNeedStart", 1);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		    startActivity(intent);
	   }*/
}
